package com.eonmind.ai.core.chat.manager;

import com.eonmind.ai.core.chat.platform.AiPlatformCache;
import com.eonmind.common.contract.enums.ErrorCode;
import com.eonmind.common.contract.exception.BusinessException;
import com.eonmind.common.provider.entity.ai.AiPlatform;
import jakarta.annotation.Resource;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.ai.chat.model.ChatModel;
import org.springframework.ai.model.SimpleApiKey;
import org.springframework.ai.openai.OpenAiChatModel;
import org.springframework.ai.openai.api.OpenAiApi;
import org.springframework.stereotype.Component;

/**
 * ChatModel 管理器
 * 用于通过模型ID获取ChatModel
 *
 * @author Xujie
 * @since 2025/5/6 21:21
 **/
@Component
public class ChatModelManager {
    @Resource
    private AiPlatformCache aiPlatformCache;

    public ChatModel getChatModel(Long modelId) {
        AiPlatform platform = aiPlatformCache.getPlatform(modelId);
        if (platform == null) {
            throw new BusinessException(ErrorCode.FAIL, "模型不存在可用的渠道");
        }
        return buildChatModel(platform);
    }

    private ChatModel buildChatModel(AiPlatform aiPlatform) {
        if (ObjectUtils.isEmpty(aiPlatform) || ObjectUtils.isEmpty(aiPlatform.getBaseUrl())
                || ObjectUtils.isEmpty(aiPlatform.getKey())) {
            throw new BusinessException(ErrorCode.FAIL, "渠道配置异常，请重新请求");
        }
        OpenAiApi openAiApi = OpenAiApi.builder()
                .baseUrl(aiPlatform.getBaseUrl())
                .apiKey(new SimpleApiKey(aiPlatform.getKey()))
                .build();
        return OpenAiChatModel.builder()
                .openAiApi(openAiApi)
                .build();
    }
}
